import classnames from 'classnames'
import { useAppSelector } from '@/store'
import Icon from '@/components/icon/index'
import styles from './index.module.scss'
import { getRecommendChannels, setActiveChannel, delChannel } from '@/store/index'
import { useInitialState } from '@/hooks/useInitialState'
import { useAppDispatch } from '@/store'
import { useState } from 'react'

const Channels = ({ hide }: { hide: () => void }) => {
  const dispatch = useAppDispatch()

  const { channels, activeChannel } = useAppSelector((state) => state.homeSlice)
  const { recommendChannels } = useInitialState(getRecommendChannels, 'homeSlice')

  // 是否为编辑状态
  const [isEdit, setIsEdit] = useState(false)
  function changeEdit() {
    setIsEdit((isEdit) => !isEdit)
  }
  // 切换我的频道编辑状态
  function onChange(id: number) {
    dispatch(setActiveChannel(id))
  }
  // 删除频道
  function handleDelChannel(id: number) {
    dispatch(delChannel(id))
  }
  return (
    <div className={styles.root}>
      <div className="channel-header">
        <Icon type="iconbtn_channel_close" onClick={hide} />
      </div>
      <div className="channel-content">
        {/* 编辑时，添加类名 edit */}
        <div className={classnames('channel-item', { edit: isEdit })}>
          <div className="channel-item-header">
            <span className="channel-item-title">我的频道</span>
            <span className="channel-item-title-extra">点击进入频道</span>
            <span className="channel-item-edit" onClick={changeEdit}>
              {isEdit ? '完成' : '编辑'}
            </span>
          </div>
          <div className="channel-list">
            {/* 选中时，添加类名 selected */}
            {channels.map((item) => (
              <span
                onClick={() => {
                  if (isEdit) return
                  onChange(item.id)
                  hide()
                }}
                key={item.id}
                className={classnames('channel-list-item', item.id === activeChannel && 'selected')}
              >
                {item.name}
                <Icon type="iconbtn_tag_close" onClick={() => handleDelChannel(item.id)} />
              </span>
            ))}
          </div>
        </div>

        <div className="channel-item">
          <div className="channel-item-header">
            <span className="channel-item-title">频道推荐</span>
            <span className="channel-item-title-extra">点击添加频道</span>
          </div>
          <div className="channel-list">
            {recommendChannels.map((item) => (
              <span key={item.id} className="channel-list-item">
                {item.name}
              </span>
            ))}
          </div>
        </div>
      </div>
    </div>
  )
}

export default Channels
